package com.thirtydays.frame.util.ext

import android.graphics.Bitmap
import android.graphics.Canvas
import android.view.View
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.PathUtils
import com.blankj.utilcode.util.TimeUtils
import com.thirtydays.frame.util.StringUtils
import java.io.File
import java.text.SimpleDateFormat
import java.util.logging.SimpleFormatter

/**
 * 保存图片到相册
 */
fun Bitmap.saveBitMap(isAdd: Boolean = true, recycle: Boolean = false): String {
    return if (isAdd) {
        val save2Album = ImageUtils.save2Album(this, Bitmap.CompressFormat.PNG, recycle)
        save2Album!!.absolutePath
    } else {
        val destFile = File(
            "${PathUtils.getFilesPathExternalFirst()}}/image",
            "${TimeUtils.getNowString(SimpleDateFormat("yyyy年MM月dd日HH:mm:ss"))}${StringUtils.getRandomString(6)}.png"
        )
        val result = destFile.absolutePath
        if (FileUtils.createOrExistsFile(destFile)) {
            ImageUtils.save(this, result, Bitmap.CompressFormat.PNG, recycle)
            result
        } else {
            result
        }
    }
}

//把当前View生成Bitmap
fun View.getBitmap(): Bitmap {
    val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bmp)
    draw(canvas)
    canvas.save()
    return bmp
}

fun View.getLayoutBitmap(): Bitmap {
    this.measure(
        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
    )
    this.layout(0, 0, measuredWidth, measuredHeight)
    val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bmp)
    draw(canvas)
    canvas.save()
    return bmp
}